import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PAGINATION_OPTIONS, TABLE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, DATETIME_FORMAT, FIXED_COLUMN_WIDTH} from '../constants';
import {PERMISSION} from './constants';
import {injectIntl} from './intl';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {hasPermissions} from './utils';
import {saleOrderStatus, saleOrderPriceTerms, saleOrderTransportType, saleOrderType, paymentType, saleOrderSource} from '../Enum';
import {abandonData, submitData} from './api';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import DropdownMenu from 'Shared/components/DropdownMenu';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }

    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onClickSubmitBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        submitData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        abandonData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    render() {
        const colums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '订单编号'
                }),
                dataIndex: 'code',
                width: '100px',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
                render: (text, record) => <Link to={routes.detail.format(record.id)} >{text}</Link>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.orderType',
                    defaultMessage: '订单类型'
                }),
                dataIndex: 'orderType',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'orderType' && this.props.sortedOrder,
                render: text => conventEnumValueToString(saleOrderType, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.transportType',
                    defaultMessage: '运输方式'
                }),
                dataIndex: 'transportType',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'transportType' && this.props.sortedOrder,
                render: text => conventEnumValueToString(saleOrderTransportType, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.paymentType',
                    defaultMessage: '付款方式'
                }),
                dataIndex: 'paymentType',
                render: text => conventEnumValueToString(paymentType, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.salesOrderPriceTerms',
                    defaultMessage: '价格条款'
                }),
                dataIndex: 'salesOrderPriceTerms',
                render: text => conventEnumValueToString(saleOrderPriceTerms, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.batchNumber',
                    defaultMessage: '批次号'
                }),
                dataIndex: 'batchNumber',
                width: '100px',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'status' && this.props.sortedOrder,
                render: text => conventEnumValueToString(saleOrderStatus, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.dataSource',
                    defaultMessage: '数据来源'
                }),
                dataIndex: 'dataSource',
                render: text => conventEnumValueToString(saleOrderSource, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.totalAmount',
                    defaultMessage: '总金额'
                }),
                dataIndex: 'totalAmount',
                render: text => formatAmount(text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.createTime',
                    defaultMessage: '创建时间'
                }),
                dataIndex: 'createTime',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'createTime' && this.props.sortedOrder,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.creatorName',
                    defaultMessage: '创建人姓名'
                }),
                dataIndex: 'creatorName',
            }];
        if(!this.props.isDealerUser)
            colums.splice(0, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealerCode',
                        defaultMessage: '总代编号'
                    }),
                    dataIndex: 'dealerCode',
                    sorter: true,
                    sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder,
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.marketDepartmentName',
                        defaultMessage: '大区名称'
                    }),
                    dataIndex: 'marketDepartmentName',
                }, {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.country',
                        defaultMessage: '国家'
                    }),
                    dataIndex: 'country',
                }
            ]);
        colums.push({
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.operation',
                defaultMessage: '操作'
            }),
            dataIndex: 'id',
            key: 'id',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (text, r) => {
                const menus = [{
                    id: PERMISSION.update,
                    children: <Link key="update" to={routes.update.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.update',
                            defaultMessage: '编辑'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update)),
                }, {
                    id: PERMISSION.submit,
                    children: (ref =>
                        <WrappedPopconfirm
                            key="submit"
                            placement="topLeft"
                            onConfirm={this.onClickSubmitBtn}
                            id={r.id}
                            onVisibleChange={ref.setMenuVisible}
                            title={this.props.intl.formatMessage({
                                id: 'tablePanel.validate.submit',
                                defaultMessage: '是否确认提交？'
                            })}>
                            <a>{
                                this.props.intl.formatMessage({
                                    id: 'tablePanel.submit',
                                    defaultMessage: '提交'
                                })
                            }</a>
                        </WrappedPopconfirm>
                    ),
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(r.options, PERMISSION.submit)),
                }, {
                    id: PERMISSION.approve,
                    children: <Link key="approve" to={routes.approve.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.approve',
                            defaultMessage: '审核'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(r.options, PERMISSION.approve)),
                }, {
                    id: PERMISSION.force,
                    children: <Link key="force" to={routes.force.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.force',
                            defaultMessage: '强制修改'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.force) && hasPermissions(r.options, PERMISSION.force)),
                }, {
                    id: PERMISSION.approve,
                    children: <Link key="operationDepartmentApprove" to={routes.finalApprove.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.operationDepartmentApprove',
                            defaultMessage: '终审'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.operationDepartmentApprove) &&
                    hasPermissions(r.options, PERMISSION.operationDepartmentApprove)),
                }, {
                    id: PERMISSION.approve,
                    children: <Link key="generalManagerApprove" to={routes.finalApprove.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.generalManagerApprove',
                            defaultMessage: '终审'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.generalManagerApprove) &&
                    hasPermissions(r.options, PERMISSION.generalManagerApprove)),
                }, {
                    id: PERMISSION.abandon,
                    children: (ref =>
                        <WrappedPopconfirm
                            key="abandon"
                            placement="topLeft"
                            onConfirm={this.onClickAbandonBtn}
                            id={r.id}
                            onVisibleChange={ref.setMenuVisible}
                            title={this.props.intl.formatMessage({
                                id: 'tablePanel.validate.abandon',
                                defaultMessage: '是否确认作废？'
                            })}>
                            <a>{
                                this.props.intl.formatMessage({
                                    id: 'tablePanel.abandon',
                                    defaultMessage: '作废'
                                })
                            }</a>
                        </WrappedPopconfirm>
                    ),
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon)),
                }];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        });
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={colums}
                    dataSource={this.props.list}
                    onChange={this.onChangeSort}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    locale={locale}
                    {...TABLE} />
            </div>
        );
    }
}

TablePanel.propTypes = {
    errorMessage: PropTypes.string.isRequired,
    list: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    list: getData(state),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch())
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
